package com.hx.datasouredemo.service;

import com.hx.datasouredemo.dao.UserMapper;
import com.hx.datasouredemo.db.DynamicDataSourceContextHolder;
import com.hx.datasouredemo.dto.UserDto;
import com.hx.datasouredemo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 使用db2数据源
     */
    public void saveUser(UserDto userDto) {
        DynamicDataSourceContextHolder.setDataSource("db2");
        User user = new User();
        user.setName(userDto.getName());
        userMapper.insert(user);
        DynamicDataSourceContextHolder.clearDataSource();
    }

    /**
     * 使用db2数据源
     */
    public List<User> selectAll1() {
        DynamicDataSourceContextHolder.setDataSource("db1");
        List<User> users = userMapper.selectAll();
        DynamicDataSourceContextHolder.clearDataSource();
        return users;
    }

    /**
     * 使用db2数据源
     */
    public List<User> selectAll2() {
        DynamicDataSourceContextHolder.setDataSource("db2");
        List<User> users = userMapper.selectAll();
        DynamicDataSourceContextHolder.clearDataSource();
        return users;
    }
}

